package com.topboya.linker.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.tencent.map.geolocation.TencentLocation;
import com.tencent.map.geolocation.TencentLocationListener;
import com.tencent.map.geolocation.TencentLocationManager;
import com.tencent.map.geolocation.TencentLocationRequest;
import com.topboya.linker.R;
import com.topboya.linker.model.levelitem.DepartmentGroupBo;
import com.topboya.linker.model.response.DictByKeyResponse;
import com.topboya.linker.model.response.DictionaryResponse;
import com.topboya.linker.model.response.TencentLocationResponse;
import com.topboya.linker.model.response.TitleDictResopnse;
import com.topboya.linker.model.response.VisitTypeResponse;
import com.topboya.linker.ui.adapter.HaspitalTypeAdapter;
import com.topboya.linker.ui.adapter.VisitypeAdapter;
import com.topboya.linker.ui.base.activity.BaseActivity;
import com.topboya.linker.ui.presenter.AddDevicesPresenter;
import com.topboya.linker.ui.view.AddDevicesView;
import com.topboya.linker.utils.LogUtils;
import com.topboya.linker.utils.PhotoBitmapUtils;
import com.topboya.linker.utils.UIUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class AddDeviceActivity extends BaseActivity<AddDevicesView, AddDevicesPresenter> implements AddDevicesView{
    private static final String TAG = "AddDeviceActivity:";
    private Toolbar toolbar;
    private TextView toolbar_title;
    private EditText et_device_name;
    private RecyclerView rcy_devicetype;
//    private TextView tv_select_devicetype;
    private TextView tv_toolbar_right;
    private TextView tv_address;
//    private LinearLayout ll_add_picture;
    private TextView tv_select_level;
    private TextView tv_select_area;
    private TextView tv_add_pic_tips;
    private RelativeLayout select_address;
    private RelativeLayout rl_add_picture;
    private ImageView img_picture;
    private ImageView img_pic_delete;
    private List<DictionaryResponse.Data> listorgtype;
    private List<DictionaryResponse.Data> listhosleve;
    private List<DictionaryResponse.Data> listarea;
    private List<String> listorgtypename;
    private List<String> listhoslevename;
    private List<String> listareaname;
    private Button btn_save;
    private ImageView img_camera_picture;
    private static final int OPEN_CAMERA = 2;
    private String address;
    private String orgType;
    private String hosLevel;
    private String orgAreaId;
    private String filePathtoJson;
    private String latitude;
    private String longitude;
    private HaspitalTypeAdapter haspitalTypeAdapter;
    private List<TencentLocationResponse.PoisList> poisLists;
    private TencentLocationResponse.PoisList poisList;


    @Override
    protected int getLayoutId() {

        return R.layout.activity_add_devices;
    }

    @Override
    protected void initView() {

        toolbar_title = findViewById(R.id.toolbar_title);
        tv_toolbar_right = findViewById(R.id.tv_toolbar_right);
//        tv_select_devicetype = findViewById(R.id.tv_select_devicetype);
        tv_address = findViewById(R.id.tv_address);
//        ll_add_picture = findViewById(R.id.ll_add_picture);
        tv_select_level = findViewById(R.id.tv_select_level);
        tv_select_area = findViewById(R.id.tv_select_area);
        btn_save = findViewById(R.id.btn_save);
        img_camera_picture = findViewById(R.id.img_camera_picture);
        et_device_name = findViewById(R.id.et_device_name);
        rcy_devicetype = findViewById(R.id.rcy_devicetype);
        select_address = findViewById(R.id.select_address);
        rl_add_picture = findViewById(R.id.rl_add_picture);
        tv_add_pic_tips = findViewById(R.id.tv_add_pic_tips);
        img_picture = findViewById(R.id.img_picture);
        img_pic_delete = findViewById(R.id.img_pic_delete);
        toolbar = findViewById(R.id.toolbar);
        initViewContent();

    }

    private void initViewContent() {

        toolbar_title.setText("新增终端");
        tv_toolbar_right.setText("保存");
        String tvtips = "<font color='#222222'>点击左侧相机图片进行拍摄或者选择照片类型为营业执照或者终端拍摄时，虚保证 </font>"+"<font color='#FF8148'>边框完整、字体清晰</font>";
        tv_add_pic_tips.setText(Html.fromHtml(tvtips));

    }

    @Override
    protected void initData() {

        poisLists = new ArrayList<>();
         initRcyView();
//        首先拿到字典数据科室和职称
        mPresenter.getLocationFromTencent();
        mPresenter.getOrgTypeFromDic("org_type");


    }

    private void initRcyView() {

        listorgtype = new ArrayList<>();
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
//        rl_visittype.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.HORIZONTAL, 2, 0xBFC0C2));
        rcy_devicetype.setLayoutManager(manager);
        haspitalTypeAdapter = new HaspitalTypeAdapter(this,listorgtype);
        rcy_devicetype.setAdapter(haspitalTypeAdapter);
    }

    @Override
    protected void initListener() {

//        tv_select_devicetype.setOnClickListener(v -> {
//
//            OptionsPickerView pvOptions = new OptionsPickerBuilder(this, (options1, option2, options3, v1) -> {
//
//                String orgtypename = listorgtypename.get(options1);
//                orgType =listorgtype.get(options1).getValue();
//                tv_select_devicetype.setText(orgtypename);
//
//            }).setCyclic(true,true,true)
//                    .setTextColorCenter(Color.BLUE)
//                    .build();
//            pvOptions.setPicker(listorgtypename , null, null);
//            pvOptions.show();
//
//        });
        toolbar.setNavigationOnClickListener(v -> {
            finish();
            jumpToActivity(xCustomerActivity.class); });
        img_pic_delete.setOnClickListener(v -> {

            img_camera_picture.setVisibility(View.VISIBLE);
            img_picture.setVisibility(View.GONE);
            img_pic_delete.setVisibility(View.GONE);

        });

        img_picture.setOnClickListener(v -> {

            Intent intent = new Intent(AddDeviceActivity.this,PictureDisplayActivity.class);
            intent.putExtra("filepath",fileName);
            startActivity(intent);


        });
        select_address.setOnClickListener(v -> {

          Intent intent = new Intent(AddDeviceActivity.this,SelectAddressActivity.class);
          intent.putExtra("poisLists", (Serializable) poisLists);
          startActivityForResult(intent,1001);

        });
        tv_select_level.setOnClickListener(v -> {

            OptionsPickerView pvOptions = new OptionsPickerBuilder(this, (options1, option2, options3, v1) -> {

                String hoslevename = listhoslevename.get(options1);
                hosLevel = listhosleve.get(options1).getValue();
                tv_select_level.setText(hoslevename);

            }).setCyclic(true,true,true)
                    .setTextColorCenter(Color.BLUE)
                    .build();
            pvOptions.setPicker(listhoslevename , null, null);
            pvOptions.show();

        });
        tv_select_area.setOnClickListener(v -> {

            OptionsPickerView pvOptions = new OptionsPickerBuilder(this, (options1, option2, options3, v1) -> {

                String areaname = listareaname.get(options1);
                orgAreaId = listarea.get(options1).getValue();
                tv_select_area.setText(areaname);

            }).setCyclic(true,true,true)
                    .setTextColorCenter(Color.BLUE)
                    .build();
            pvOptions.setPicker(listareaname , null, null);
            pvOptions.show();

        });
        // 启动相机
        rl_add_picture.setOnClickListener(v -> addBitmapShoots());

        tv_toolbar_right.setOnClickListener(v ->{

                    String orgName = et_device_name.getText().toString().trim();
                    List selcted = haspitalTypeAdapter.getSelectedItem();
                    String orgType="";
                    if (null !=selcted && selcted.size() >0){

                         orgType = haspitalTypeAdapter.getSelectedItem().get(0).getValue();
                    }

                    LogUtils.v(TAG + "orgName:"+orgName);
                    LogUtils.v(TAG + "address:"+address);
                    LogUtils.v(TAG + "orgType:"+orgType);
                    LogUtils.v(TAG + "latitude:"+latitude);
                    LogUtils.v(TAG + "longitude:"+longitude);
                    LogUtils.v(TAG + "filePathtoJson:"+filePathtoJson);
                    LogUtils.v(TAG + "hosLevel:"+hosLevel);
                    LogUtils.v(TAG + "orgAreaId:"+orgAreaId);
                    judgeEmptyCreatDevice(orgName,orgType);

                }
              );
    }

    private void judgeEmptyCreatDevice(String orgName ,String orgType) {

        if (TextUtils.isEmpty(orgName)  ){
            UIUtils.showToast("请输入终端名称");
            return;
        }
        if (TextUtils.isEmpty(orgType)){

            UIUtils.showToast("请选择终端类型");
            return;
        }
        if (TextUtils.isEmpty(latitude)||TextUtils.isEmpty(longitude)){

            UIUtils.showToast("请选择地址");
            return;
        }

        if ( TextUtils.isEmpty(filePathtoJson)){

            UIUtils.showToast("请先上传证件照片");
            return;
        }
        if (TextUtils.isEmpty(hosLevel) ){

            UIUtils.showToast("请先选择医院等级");
            return;
        }
        if ( TextUtils.isEmpty(orgAreaId)){

            UIUtils.showToast("请先选择区域");
            return;
        }
        mPresenter.creatOrg(orgName,address,orgType,latitude,longitude,filePathtoJson,hosLevel,orgAreaId);

    }

    @Override
    protected AddDevicesPresenter createPresenter() {

        return new AddDevicesPresenter(this);
    }


    @Override
    public void setPickViewData(List<DictionaryResponse.Data> listorgtype, List<DictionaryResponse.Data> listhosleve, List<DictionaryResponse.Data> listarea) {


//        this.listorgtype = listorgtype;
        this.listhosleve = listhosleve;
        this.listarea = listarea;
        this.listorgtype.addAll(listorgtype);
        haspitalTypeAdapter.notifyDataSetChanged();
        listorgtypename = new ArrayList<>();
        listhoslevename = new ArrayList<>();
        listareaname = new ArrayList<>();

        for (DictionaryResponse.Data listorgtype1:listorgtype) {
            listorgtypename.add(listorgtype1.getLabel());
        }


        for (DictionaryResponse.Data listhosleve1:listhosleve) {
            listhoslevename.add(listhosleve1.getLabel());
        }

        for (DictionaryResponse.Data listarea1:listarea) {
            listareaname.add(listarea1.getLabel());
        }

    }

    @Override
    public void setLoaction(List<TencentLocationResponse.PoisList> poisLists, String latitude, String longitude) {

          this.poisLists.clear();
          this.poisLists.addAll(poisLists);
          this.poisList = poisLists.get(0);
          this.address = poisLists.get(0).getAddress();
          this.latitude = latitude;
          this.longitude = longitude;
          tv_address.setText(address);
    }


    @Override
    public void upLoadFileSuc(String filePath) {

         UIUtils.showToast("照片上传成功:"+filePath);
        filePathTOjson(filePath);
    }

    private void filePathTOjson(String filePath) {

        JSONObject jsonObject = new JSONObject();
        try {
            filePathtoJson= jsonObject.put("address",filePath).toString().replace("\\/", "/");
            LogUtils.v(TAG + "filePathtoJson:"+filePathtoJson);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void creatOrgSuc() {

//        创建终端成功
         finish();
        jumpToActivity(xCustomerActivity.class);

    }

    String fileName = "";
    /**
     * 启动相机拍照
     */
    private void addBitmapShoots() {

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 设置图片要保存的 根路径+文件名
        fileName = PhotoBitmapUtils.getPhotoFileName(this);
        LogUtils.v(TAG + "fileNme:"+fileName);
        File file = new File(fileName);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        startActivityForResult(intent, OPEN_CAMERA);
    }
    private String filepath;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        // 获取相机拍照返回
        if (resultCode == Activity.RESULT_OK && requestCode == OPEN_CAMERA) {
            // 得到修复后的照片路径
            filepath = PhotoBitmapUtils.amendRotatePhoto(fileName, this);
            LogUtils.v(TAG + filepath);
            img_camera_picture.setVisibility(View.GONE);
            img_picture.setVisibility(View.VISIBLE);
            img_pic_delete.setVisibility(View.VISIBLE);
            LogUtils.v(TAG + "filepath;;;"+filepath);
            Glide.with(this).load(filepath).into(img_picture);
            mPresenter.upLoadFile(filepath);
        }

        if (resultCode ==1002){

            poisList = (TencentLocationResponse.PoisList) data.getSerializableExtra("poisList");
            if (null!=poisList){

                tv_address.setText(poisList.getAddress());
                this.latitude = poisList.getLocation().getLat();
                this.longitude = poisList.getLocation().getLng();

            }
        }
    }

    //将图片文件添加至相册（便于浏览）
//    private void galleryAddPic() {
//        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
//        Uri contentUri = Uri.fromFile(photoFile);
//        mediaScanIntent.setData(contentUri);
//        this.sendBroadcast(mediaScanIntent);
//    }

    @Override
    public void onBackPressed() {

        back();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 是否触发按键为back键
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed();
            return true;
        } else { // 如果不是back键正常响应
            return super.onKeyDown(keyCode, event);
        }
    }

    private void back() {


         finish();
        jumpToActivity(xCustomerActivity.class);

    }

}
